package com.zzh.interview.job.once;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import com.zzh.interview.esdao.QuestionEsDao;
import com.zzh.interview.model.dto.question.QuestionEsDTO;
import com.zzh.interview.model.entity.Question;
import com.zzh.interview.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.collection.CollUtil;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 全量同步题目到 es
 * @author <a href="https://gitee.com/zzhpalus">zzhKing</a>
 * @from <a href="https://gitee.com/zzhpalus">致力于学习</a>
 */

//实现CommandLineRunner接口，再启动项目注入到Bean对象时就会自动执行run一次
// todo 取消注释开启任务
//@Component
@Slf4j
public class FullSyncQuestionToEs implements CommandLineRunner {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionEsDao questionEsDao;


    @Override
    public void run(String... args) {
        //首先直接全量查询题目数据，因为题目本身也不多！
        List<Question> postList = questionService.list();
        if (CollUtil.isEmpty(postList)) {
            return;
        }
        //将question 转成 对应es存储的 DTO对象
        List<QuestionEsDTO> questionEsDTOList = postList.stream().map(QuestionEsDTO::objToDto).collect(Collectors.toList());
        //分批保存到es
        final int pageSize = 500;
        int total = questionEsDTOList.size();
        log.info("FullSyncPostToEs start, total {}", total);
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, total);
            log.info("sync from {} to {}", i, end);
            //批量保存到es
            questionEsDao.saveAll(questionEsDTOList.subList(i, end));
        }
        log.info("FullSyncPostToEs end, total {}", total);
    }
}
